//
//  Cipher.m
//  HiZhua
//
//  Created by Jpwang on 2017/8/5.
//  Copyright © 2017年 Jpwang. All rights reserved.
//

#import "Cipher.h"
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>

@implementation Cipher

//10进制转16进制
NSString * ToHex(long long tmpid) {
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig) {
            case 10:
                nLetterValue = @"a";break;
            case 11:
                nLetterValue = @"b";break;
            case 12:
                nLetterValue = @"c";break;
            case 13:
                nLetterValue = @"d";break;
            case 14:
                nLetterValue = @"e";break;
            case 15:
                nLetterValue = @"f";break;
            default:
                nLetterValue = [[NSString alloc] initWithFormat:@"%lli",ttmpig];
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            if (str.length == 1) {
                str = [NSString stringWithFormat:@"0%@",str];
            }
            break;
        }
    }
    return str;
}


//hmacsha1签名
NSString * hmacsha1(NSString *text, NSString * secret) {
    NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[20];
    CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], result);
    NSString *data = @"";
    for (int i=0; i<sizeof(result); i++) {
        int number = result[i];
        NSString *hex  = ToHex(number);
        data = [NSString stringWithFormat:@"%@%@",data, hex];
    }
    return data;
}

@end
